<template>
  <a-upload
      :fileList="[files]"
      :custom-request="handleUpload"
      :show-file-list="false"
      image-preview>
    <template #upload-button>
      <div :class="`arco-upload-list-item${files ? ' arco-upload-list-item-error' : '' }`">
        <div class="arco-upload-list-picture custom-upload-avatar" v-if="files && files.url">
          <img :src="files.url"/>
          <div class="arco-upload-list-picture-mask">
            <IconEdit/>
          </div>
        </div>
        <div class="arco-upload-picture-card" v-else>
          <div class="arco-upload-picture-card-text">
            <IconPlus/>
            <div>{{ tip }}</div>
          </div>
        </div>
      </div>
    </template>
  </a-upload>
</template>

<script setup lang="ts">
import {Message, type RequestOption} from '@arco-design/web-vue'
import {uploadImages} from '@/api/common'

const props = withDefaults(
    defineProps<
        Partial<{
          modelValue: string | Array<string>;
          limit: number;
          tip: string
        }>
    >(),
    {
      limit: 1,
      tip: '100 × 100'
    }
);


const emits = defineEmits(['update:modelValue']);
const files = computed({
  get() {
    return {url: props.modelValue};
  },
  set(e) {
    emits('update:modelValue', e);
  },
});
// 上传
const handleUpload = (options: RequestOption) => {
  const controller = new AbortController()
  ;(async function requestWrap() {
    const {onProgress, onError, onSuccess, fileItem, name = 'file'} = options
    onProgress(20)
    const formData = new FormData()
    formData.append(name as string, fileItem.file as Blob)
    try {
      const res = await uploadImages(formData)
      files.value = res.data.url
      Message.success('上传成功')
      onSuccess(res)
    } catch (error) {
      onError(error)
    }
  })()
  return {
    abort() {
      controller.abort()
    },
  }
}

</script>

<style scoped lang="less">

</style>